﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Text;
using System.Drawing.Imaging;
using System.Text;

public partial class Captcha : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // lay thoi gian hien tai (milligiay) va ma hoa dang base64
        byte[] timeData = Encoding.ASCII.GetBytes(DateTime.Now.Ticks.ToString());
        String captchaCode = Convert.ToBase64String(timeData).ToUpper();
        System.Threading.Thread.Sleep(10);
        // lay 1 so ngau nhien
        String kytungaunhien = AllCode.Utils.TaoChuoiNgauNhien(6);
        //captchaCode = captchaCode + kytungaunhien;
        // lay 5 ky tu dau cua chuoi da duoc ma hoa va luu vao session
        Session["Captcha"] = kytungaunhien;//captchaCode.Substring(captchaCode.Length - 6);
        
        // tao anh trong
        Bitmap image = new Bitmap(70, 22);
        // lay moi truong do hoa cua anh de chuan bi ve len anh
        Graphics g = Graphics.FromImage(image);
        // do mau nen cho anh
        g.Clear(Color.AliceBlue);
        // thiet lap che do hien thi chuoi
        g.TextRenderingHint = TextRenderingHint.AntiAlias;
        // tao font cho chuoi sap ve
        Font font = new Font("Comic Sans MS", 12, FontStyle.Bold);
        // ve chuoi da lu vao session len anh voi font chu va mau tai vi tri 0, 0
        g.DrawString(Session["Captcha"].ToString(), font, Brushes.Red, 0, 0);

        // yeu cau trinh duyet hien thi Captcha.aspx nhu la hinh anh
        Response.ContentType = "image/gif";
        // ghi du lieu hinh len luong ra de gui ve trinh duyet
        image.Save(Response.OutputStream, ImageFormat.Gif);
        // giai phong cac tai nguyen lien quan: font, moi truong do hoa va anh
        font.Dispose();
        g.Dispose();
        image.Dispose();
    }
}